package user_logic

import (
	"context"
	"fmt"
	"time"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewDeleteUserLogic 删除用户
func NewDeleteUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteUserLogic {
	return &DeleteUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteUserLogic) DeleteUser(req *types.DeleteUserRequest) (resp *types.UserResponse, err error) {
	// 验证输入数据
	if req.Username == "" {
		return &types.UserResponse{
			Code:    500,
			Message: "用户名不能为空"}, fmt.Errorf("用户名不能为空")
	}

	// 判断使用的数据库类型
	flag := l.svcCtx.Config.UseMysql

	currentTime := time.Now()
	format := currentTime.Format("2006-01-02 15:04:05.000")
	var updateSQL string
	if flag {
		updateSQL = fmt.Sprintf("UPDATE %s SET deleted_at = '%s' WHERE username = ? AND deleted_at IS NULL", l.svcCtx.Config.Mysql.Tables.UserInfoTable, format)
	} else {
		updateSQL = fmt.Sprintf("UPDATE %s SET deleted_at = '%s' WHERE username = ? AND deleted_at IS NULL", l.svcCtx.Config.SQLite.Tables.UserInfoTable, format)
	}

	// 执行逻辑删除，更新 deleted_at 字段
	result, err := l.svcCtx.Conn.Exec(updateSQL, req.Username)
	if err != nil {
		return &types.UserResponse{
			Code:    500,
			Message: "用户删除失败: " + err.Error()}, fmt.Errorf("failed to logically delete user: %v", err)
	}

	// 获取受影响的行数
	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return nil, fmt.Errorf("failed to get rows affected: %v", err)
	}

	// 检查是否找到并逻辑删除了用户
	if rowsAffected == 0 {
		return &types.UserResponse{
			Code:    500,
			Message: "删除失败, 用户不存在"}, fmt.Errorf("user not found")
	}

	return &types.UserResponse{
		Code:    200,
		Message: "用户删除成功"}, nil
}
